import { IEvent, IWindowState } from "./model";
import { dispatch as appDispatch } from "./app-state";
import { onStatusChanged, IWinStatus, getWinStatus } from "../utils/win-util";

function compare (newS: IWindowState, oldS: IWindowState): IWindowState {
  if (!oldS) {
    return newS;
  }
  if (newS.width != oldS.width || newS.height != oldS.height ||
    newS.isMaximize != oldS.isMaximize || newS.isMinimize != oldS.isMinimize) {
      return newS;
  } else {
    return oldS;
  }
}

function onUpdate (e: IEvent, s: IWindowState): IWindowState {
  const winStatus: IWinStatus = e.data || getWinStatus();
  const result = compare({
    width: winStatus.width,
    height: winStatus.height,
    isMaximize: winStatus.isMaximized,
    isMinimize: winStatus.isMinimized,
  }, s);
  return result;
}

export function dispatch (e: IEvent, s: IWindowState): IWindowState {
  if (e.type == 'app.init') {
    return onUpdate(e, s);
  } else if (e.type == 'win.updated') {
    return onUpdate(e, s);
  } else {
    return s;
  }
}

onStatusChanged((s) => {
  appDispatch({
    type: 'win.updated',
    data: s
  });
});


